package uk.gov.swmprobation.cpvisibility;

import java.util.ArrayList;

import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.MapView.Projection;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.OverlayItem;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

public class CreateProject extends MyActivity {
	
	private MyOpenViewMap myOpenMapView;
	private MapController myMapController;
	private GeoPoint point;
	private Project project;
	private boolean placePointer = false;
	
	static WifiManager wifi;
	BroadcastReceiver receiver;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//Show Hint each time until setting changed
		if (sharedPref.getBoolean(SettingsActivity.moveHintTitle, true)){
			Helper.showHintDialog(this, SettingsActivity.moveHintTitle, SettingsActivity.moveHintMessage);
		}
		setContentView(R.layout.activity_create_project);
		
		initVariables();
		
		ImageView photo = (ImageView) findViewById(R.id.photo);
		photo.setImageURI(project.getImageUrl());
		    
        myOpenMapView.setBuiltInZoomControls(false);
        myOpenMapView.setOnTouchListener(mapTouchListener);
        myMapController.setZoom(19);
        myMapController.setCenter(point);
        myOpenMapView.allowScroll=true;
        myOpenMapView.allowZoom=true;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.application_menu, menu);
		return true;
	}

	private void initVariables(){
		Bundle extras = getIntent().getExtras();
		int id = extras.getInt("id");
		project = DatabaseHandler.getProject(id);
		myOpenMapView = (MyOpenViewMap)findViewById(R.id.openmapview);
		myMapController = myOpenMapView.getController();
        point = new GeoPoint(project.getLat(), project.getLng());
	}
	
	private OnTouchListener mapTouchListener = new OnTouchListener(){

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (placePointer){
				int Action = event.getAction();
				if (Action == MotionEvent.ACTION_MOVE || Action == MotionEvent.ACTION_UP || Action==MotionEvent.ACTION_DOWN){
					Projection projection = myOpenMapView.getProjection();
		        	point = (GeoPoint) projection.fromPixels(event.getX(), event.getY());
		        	project.setLat(point.getLatitudeE6()/1000000.0);
		            project.setLng(point.getLongitudeE6()/1000000.0);
		            myOpenMapView.getOverlays().clear();
		            addMarker();
		            myOpenMapView.invalidate();
				}
				if (Action == MotionEvent.ACTION_UP){
					//Show Hint each time until setting changed
					if (sharedPref.getBoolean(SettingsActivity.submitHintTitle, true)){
						Helper.showHintDialog(CreateProject.this, SettingsActivity.submitHintTitle, SettingsActivity.submitHintMessage);
					}
				}
			}
			return true;
		}};
	
	private void addMarker(){
		Drawable markerImage=getResources().getDrawable(R.drawable.markergreen);
        
        markerImage.setBounds(0, 0, markerImage.getIntrinsicWidth(),
                                markerImage.getIntrinsicHeight());
        
        ArrayList<OverlayItem> markerItems = new ArrayList<OverlayItem>();
        
        OverlayItem markerItem = new OverlayItem("Location", "Location of Picture", point);
        markerItem.setMarker(markerImage);
        
        markerItems.add(markerItem);
        
        ItemizedIconOverlay<OverlayItem> markerOverlay = new ItemizedIconOverlay<OverlayItem>(this, markerItems, null){
        	public boolean onFling(android.view.MotionEvent pEvent1,
                    android.view.MotionEvent pEvent2,
                    float pVelocityX,
                    float pVelocityY,
                    MapView pMapView){
						return placePointer;
        		
        	}
        };

        myOpenMapView.getOverlays().add(markerOverlay);
	}
	
	public void submitProject(View view) {
		if(Helper.checkWifi(this)){
			//If Wifi is available send straight away
			sendNow(project.getId());
		} else {
			//If not send as per users setting
			int wifiCode = Integer.parseInt(sharedPref.getString("pref_wait_wifi", "2"));
			switch (wifiCode){
				case 1:
					delaySending();
					break;
				case 2:
					View checkBoxView = View.inflate(this, R.layout.save_setting, null);
					final CheckBox checkBox = (CheckBox) checkBoxView.findViewById(R.id.savesettingcheck);
					AlertDialog.Builder builder = new AlertDialog.Builder(this);
					builder.setMessage("Would you like to send now anyway?");
				    builder.setTitle("Wifi not available");
				    builder.setView(checkBoxView);
					builder.setPositiveButton("Send Now", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					        	   if (checkBox.isChecked()){
					        		   sharedPref.edit().putString("pref_wait_wifi","3").commit();
					        	   }
					        	   sendNow(project.getId());
					           }
					       });
					builder.setNegativeButton("Wait for Wifi", new DialogInterface.OnClickListener() {
					           public void onClick(DialogInterface dialog, int id) {
					        	   if (checkBox.isChecked()){
					        		   sharedPref.edit().putString("pref_wait_wifi","1").commit();
					        	   }
					        	   delaySending();
					           }
					       });

					AlertDialog dialog = builder.create();
					dialog.show();
					break;
				case 3:
					sendNow(project.getId());
					break;
				default:
					
			}	
		}
	  }
	public void switchMovement(View view){
		if (placePointer){
			//Move map mode
			findViewById(R.id.marker_button).setVisibility(View.VISIBLE);
			findViewById(R.id.move_button).setVisibility(View.GONE);
			TextView touchInstructions = (TextView)findViewById(R.id.touchinstruction);
			touchInstructions.setText("Move map to location");
			//Show Hint each time until setting changed
			if (sharedPref.getBoolean(SettingsActivity.moveHintTitle, true)){
				Helper.showHintDialog(this, SettingsActivity.moveHintTitle, SettingsActivity.moveHintMessage);
			}
		} else {
			//Place marker mode
			findViewById(R.id.marker_button).setVisibility(View.GONE);
			findViewById(R.id.move_button).setVisibility(View.VISIBLE);
			TextView touchInstructions = (TextView)findViewById(R.id.touchinstruction);
			touchInstructions.setText("Touch actual location on map");
			//Show Hint each time until setting changed
			if (sharedPref.getBoolean(SettingsActivity.markerHintTitle, true)){
				Helper.showHintDialog(this, SettingsActivity.markerHintTitle, SettingsActivity.markerHintMessage);
			}
		}
		placePointer = !placePointer;
		myOpenMapView.allowScroll=!myOpenMapView.allowScroll;
	}
	private void sendNow(int localId){
		project.setProjectStatus("Waiting");
		project.save();
		Intent serviceIntent = new Intent(this, SendWaiting.class);
		serviceIntent.putExtra("localId", localId);
		this.startService(serviceIntent);
		finish();
	}
	
	private void delaySending(){
		project.setProjectStatus("Waiting");
		project.save();
		finish();
	}

	public void deleteProject(View view) {
		int localId = project.getId();
        DatabaseHandler.deleteProject(localId);
        finish();
	}

}
